package customfields;

import log.Logger;
import net.rim.device.api.system.Display;
import net.rim.device.api.ui.Color;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.Graphics;

public class FileField extends Field{
	
	private String text;
	private int height;
	private int width;
	private int padding = 10;
	private int textColorUnfocused = Color.BLACK;
	private int textColorFocused = Color.WHITE;
	private int textColor;

	public FileField(String name, long style){
		super(style);
		this.text = name;
		height = (int) (getFont().getHeight());  
		width = (int) (Display.getWidth()*0.9); 
	}

	public FileField(String txt, long style, int w, int h){
		super(style);
		this.text = txt;
		height = w;  
		width = h; 
	}

	public FileField(String txt){
		super();
		this.text=txt;
		height = (int) (getFont().getHeight());  
		width = (int) (Display.getWidth()*0.9); 
	}

	public int getPreferredWidth() {  
		return width;  
	}  

	public int getPreferredHeight() {  
		return height;  
	}  

	protected void onFocus(int direction) {
		textColor = textColorFocused; 
		invalidate();  
	}  

	protected void onUnfocus() {  
		textColor = textColorUnfocused;  
		invalidate();  
	} 

	protected void layout(int arg0, int arg1) {  

		setExtent(getPreferredWidth(), getPreferredHeight());  
	}  
	
	
	protected void fieldChangeNotify(int context) {
		try {
			this.getChangeListener().fieldChanged(this, context);
		}
		catch (Exception e) {
			Logger.log("field error");
		}
	}


	protected boolean navigationClick(int status, int time) {
		fieldChangeNotify(1);
		return true;
	}

	protected void paint(Graphics graphics) {
		// draw text: left aligned
		graphics.setColor(textColor);
		if(getFont().getAdvance(text)>getWidth()){
			text = dot(text);
		}
		graphics.drawText(text,padding,0);
	}
	
	private String dot(String word){
		word = word.substring(0,word.length()-1);
		while (getFont().getAdvance(word+" (...)")>(getWidth()-50)){
			word = word.substring(0,word.length()-1);
		}
		return word+" (...)";
	}
}
